
import Sumo3D from './sumo3d'
import * as _ from 'lodash';

export default function createStore(init) {
  const { webSocket } = init;
  const sumo3d = new Sumo3D(init.sumoRootEl, init);
  const state = {}
  setTimeout(()=>{
    console.log('开始～～～～～～～～～');
    
    webSocket.send(JSON.stringify({type: 'action', action: 'start'}));
  },2000)
  webSocket.onmessage = event => {
    const msg = JSON.parse(event.data);

    if (msg.type === 'snapshot') {
      const payloadSize = event.data.length;
      state.stats = {
        time: msg.time,
        payloadSize,
        vehicleCounts: msg.vehicle_counts,
        simulateSecs: msg.simulate_secs,
        snapshotSecs: msg.snapshot_secs,
      };

      processDelta(msg.vehicles, {
        enter: (vehicleId, info) => sumo3d.createVehicleObject(vehicleId, info),
        update: (vehicleId, info) => sumo3d.updateVehicleObject(vehicleId, info),
        exit: vehicleId => sumo3d.removeVehicleObject(vehicleId),
      });

      processDelta(msg.lights, {
        enter: (lightId, delta) => sumo3d.updateLightObject(lightId, delta),
        update: (lightId, delta) => sumo3d.updateLightObject(lightId, delta),
        exit: id => console.warn('Disappearing traffic lights!', id),
      });
   
      sumo3d.render()
    } else if (msg.type === 'state') {
      state.simulationStatus = msg.simulationStatus;
      state.delayMs = msg.delayMs;
    } else {
      console.error('unrecognized message: ', msg);
    }
  };
}

function processDelta(delta,callbacks) {
  _.forEach(delta.creations, (v, k) => {
    callbacks.enter(k, v);
  });
  _.forEach(delta.updates, (v, k) => {
    callbacks.update(k, v);
  });
  _.forEach(delta.removals, v => {
    callbacks.exit(v);
  });
}